import os
import asyncio


async def run_cmd(cmd, async_flag=False):
    if async_flag:
        ret = os.system(cmd)
        print(f"shell command: {cmd} , ret:{ret}")
        return

    process = await asyncio.create_subprocess_shell(
        cmd,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )

    stdout, stderr = await process.communicate()
    print(f"[{cmd!r} exited with {process.returncode}]")
    if stdout:
        print(f"[stdout]\n{stdout.decode()}")
    if stderr:
        print(f"[stderr]\n{stderr.decode()}")


async def loop_print():
    while True:
        print("loop_print")
        await asyncio.sleep(2)


async def asyncio_main():
    async_flag = False
    cmd = "sleep 30; ls /"
    task = asyncio.gather(run_cmd(cmd, async_flag), loop_print())
    await task


if __name__ == "__main__":
    asyncio.run(asyncio_main())

# 测试1:
""" 当 async_flag = True , loop_print一直运行
loop_print
loop_print
...
"""

# 测试2:
""" 当 async_flag = False , loop_print阻塞 30s之后才打印
...
"""
